import { Notifications } from '/imports/models/Notifications';

Template.header_notifications.onCreated(function() {
  this.query = { user_id: Meteor.userId() };
  this.limit = new ReactiveVar(10);

  this.autorun(() => {
    this.resultSub = this.subscribe('get.unread.notifications', this.query, this.limit.get());
    this.total = Counts.get('get.unread.notifications.counts');
  });
});

Template.header_notifications.onRendered(function() {
  let ps = new PerfectScrollbar('#notification-dropdown-ps');
  $('#notification-dropdown').on('shown.bs.dropdown', () => {
    ps.update();
  });

  this.autorun(() => {
    $('#notification-dropdown-ps').on('ps-y-reach-end', () => {
      let lmt = this.limit.get();

      if (this.total >= lmt) {
        this.limit.set(lmt + 10);
      }
    });
  });
});

Template.header_notifications.helpers({
  results: function() {
    return Notifications.find({
      read: false,
      user_id: Meteor.userId()
    }, {
      limit: Template.instance().limit.get(),
      sort: { createdAt: -1 }
    });
  },
  loading: function() {
    return !Template.instance().resultSub.ready();
  }
});

Template.header_notifications.events({
  'click #notification-dropdown-ps'(event) {
    event.stopPropagation();
  },
  'click .mark-all-read'(event) {
    event.preventDefault();
    Meteor.call('markAllRead');
  }
});